from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import base64


key = b'aoqfvfrgtyhhhjty1544fskokojfqbtu'
iv = b'dstghtyhkowmtedy'


#加密
def aes_encrypt(plaintext):
    padder = padding.PKCS7(128).padder()
    padded_plaintext = padder.update(plaintext) + padder.finalize()

    cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
    encryptor = cipher.encryptor()
    ciphertext = encryptor.update(padded_plaintext) + encryptor.finalize()

    return ciphertext
#解密
def aes_decrypt(ciphertext):
    cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
    decryptor = cipher.decryptor()
    padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize()

    unpadder = padding.PKCS7(128).unpadder()
    plaintext = unpadder.update(padded_plaintext) + unpadder.finalize()

    return plaintext


#使用方法
# 待加密的中文字符串
# plaintext_str = '你dsadasd。'
# plaintext = plaintext_str.encode('utf-8')
# 加密
# ciphertext = aes_encrypt(plaintext)
# 将加密后的结果转换成 Base64 字符串
# encrypted_text_base64 = base64.b64encode(ciphertext).decode('utf-8')
# 解密
# decrypted_text = aes_decrypt(ciphertext).decode('utf-8')

